﻿using BCCommon;
using BCCommon.Enums;
using BCData.Common.Area;
using BCData.Common.Dictionary;
using BCData.Sim.Admin.Admin;
using BCData.Sim.Company.Company;
using BCData.TMS.Agent.AgentApplication;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Agent.AgentApplicationRecord;
using BCEntity.TMS.Agent.AgentApplication;
using BCService.Utils;
using Newtonsoft.Json;
using System;

namespace BCService.TMS.Agent.AgentApplication
{
    public class AgentApplicationRecordService : IAgentApplicationRecordService
    {
        private readonly IAgentApplicationRecordData agentApplicationRecordData;
        private readonly IDatabaseContext databaseContext;
        private readonly IProvinceData provinceData;
        private readonly ICityData cityData;
        private readonly ICountyData countyData;
        private readonly ICompanyData companyData;
        private readonly IAdminData adminData;

        public AgentApplicationRecordService(IAgentApplicationRecordData agentApplicationRecordData, 
            IDatabaseContext databaseContext, 
            IProvinceData provinceData, 
            ICityData cityData, 
            ICountyData countyData, 
            ICompanyData companyData, 
            IAdminData adminData)
        {
            this.agentApplicationRecordData = agentApplicationRecordData;
            this.databaseContext = databaseContext;
            this.provinceData = provinceData;
            this.cityData = cityData;
            this.countyData = countyData;
            this.companyData = companyData;
            this.adminData = adminData;
        }

        public AgentApplicationRecordDto Add(AdminDto admin, AgentApplicationRequestDto requestDto)
        {
            var adminEntity = this.adminData.GetAdmin(requestDto.Company.CompanyAdminId).Result;
            if (adminEntity == null)
            {
                throw new ArgumentException("负责人信息不存在");
            }
            requestDto.Company.AdminFullName = adminEntity.FullName;
            AgentApplicationRecordEntity entity = new AgentApplicationRecordEntity()
            {
                ApplyCode = Guid.NewGuid().ToString(),
                ApprovalStatus = ApprovalStatus.Approval.ToString(),
                CreateAdminId = admin.AdminId,
                CreateAdminName = admin.FullName,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Remark = requestDto.Remark
            };
            entity.Content = JsonConvert.SerializeObject(requestDto);
            
            return this.agentApplicationRecordData.Insert(entity).GetAwaiter().GetResult().As<AgentApplicationRecordDto>();
        }
    }
}
